<?php

namespace Wechat\Controller;

class FinishedProductController extends CommonController {


    public function index() {
        if(!check_role($this->customer["customer_id"], "1,2,3,7,8,10,11")){
            $this->error("您没有访问权限！");
            exit();
        }
        $this->assign("access", check_role($this->customer["customer_id"], "1,2,3,7,8,10,11"));
        $this->assign("supplier",$_REQUEST["supplier"]);

        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $this->assign("user",$user);
        if($_REQUEST["classId"] != "")
            $this->assign("classId",$_REQUEST["classId"]);
        $this->display("index");
    }

    public function quickOrder() {
        $this->display("quickOrder");
    }

    public function quickOrderDetail() {
//        if(!check_access($this->customer["customer_id"], "0")){
//            $this->error("您没有访问权限！");
//            exit();
//        }
        $id = $_REQUEST["id"];
        $quickProduct = D("FinishedProduct")->queryById($id);

        $quickProduct["price"] = $_REQUEST["p"];
        $quickProduct["type"] = $_REQUEST["t"];
        $quickProduct["quota"] = $_REQUEST["q"];
        $quickProduct["quick_order_code"] = $_REQUEST["code"];

        $this->assign("quickProduct", $quickProduct);
        $this->display("quickOrderDetail");

    }


    public function getQuickOrderList() {
        $classId = I("post.classId");
        if(!isNullOrEmpty($classId)) {
            $map["p.category_id"] = $classId;
        }

        $list = D("Product")->alias("p")
            ->where($map)
//            ->field("p.product_id,p.product_name,c.is_finished")
            ->select();

        echo json_encode($list);

    }

    public function quickAgentList() {
        $code = I("post.code");
        if(isNullOrEmpty($code)) {
            echo json_encode(null);
            return;
        }else{
            $map["qa.quick_agent_code"] = $code;
        }

        $quickAgent = D("QuickAgent")->alias("qa")
            ->where($map)->find();

        switch($quickAgent["type"]) {
            case 1:
                $listAll = D("Product")->alias("p")
//                    ->where($map)
                    ->select();
                break;
            case 2:
                $listAll = D("FinishedProduct")->alias("fp")
//                    ->where($map)
                    ->field("fp.*, fp.finished_product_id as product_id,fp.name as show_name,fp.function as description")
                    ->select();
                break;
            default :
                $listAll = null;
        }

        $idList = explode(',', $quickAgent["quick_agent_product_id"]);
        $priceList = explode(',', $quickAgent["quick_agent_product_price"]);

        $list = array();
        foreach($listAll as $item){
            for($i = 0; $i < sizeof($idList); $i++){
                if($idList[$i] == $item["product_id"]){
                    $item["price"] = $priceList[$i];
                    $item["type"] = $quickAgent["type"];
                    $item["quota"] = $quickAgent["quota"];
                    $item["code"] = $code;
                    array_push($list, $item);
                }
            }
        }

        echo json_encode($list);

    }

    public function FinishedProductList() {

        $classId = I("post.classId");
        $keyword = I("post.keyword");
        $supplier = I("post.supplier");

        if($classId == "17" and !check_role($this->customer["customer_id"], "1"))
            $classId = "";

        if(!isNullOrEmpty($classId)) {
            $map["fp.class_id"] = $classId;
        }else{
            if(!check_role($this->customer["customer_id"], "1"))
                $map["fp.class_id"] = array('neq','17');
        }
        if(!isNullOrEmpty($keyword)) {
            $map["fp.name"] = array('like','%'.$keyword.'%');
        }
        if(!isNullOrEmpty($supplier)) {
            $map["sl.supplier_name"] = $supplier;
        }
        $employee = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $map["fp.enterprise_code"] = $employee["enterprise_code"];
        $list = D("FinishedProduct")->alias("fp")
            ->join("left join __CLASS__ cl on cl.class_id = fp.class_id")
            ->join("left join __SUPPLIER__ sl on sl.supplier_id = fp.supplier_id")
            ->order("fp.count desc")
            ->where($map)
            ->field("fp.*,cl.class_name, sl.supplier_name")
            ->select();

        echo json_encode($list);

    }

    public function finishedOrder() {
        if(!check_role($this->customer["customer_id"], "1,2,3,7,8,10,11,14")){
            $this->error("您没有访问权限！");
            exit();
        }
        $id = $_REQUEST["id"];
        $finishedProduct = D("FinishedProduct")->queryById($id);
//        if(isNullOrEmpty($finishedProduct)) {
//            $this->redirect(U("product/index"));
//        }
        $map["finished_product_id"] = $id;
        $agentList = D('Agent')
            ->where($map)
            ->select();
        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $agentId = $user["agent_id"];

        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $this->assign("user", $user);
        $this->assign("finishedProduct", $finishedProduct);
        $this->assign("agentList", $agentList);
        $this->assign("agentId", $agentId);
        if(sizeof(explode(',',$agentId)) == 1){
            $defaultAgent = D("Agent")->where(array('agent_id'=>$agentId))->find();
            $this->assign("defaultAgent", $defaultAgent);
        }

        $this->display("finishedOrder");

    }

    public function createOrder() {

        $lastOrder = D("FinishedOrder")->alias("fo")
            ->order("fo.finished_order_id desc")
            ->limit(1)
            ->select();
//        echo($lastOrder[0]["finished_order_no"]);

        $finishedProductId = $_REQUEST["finishedProductId"];
        $finishedProduct = D("FinishedProduct")->queryById($finishedProductId);
        $data["code"] = 200;


        if(isNullOrEmpty($finishedProduct)) {
            $data["code"] = -1;
            $data["msg"] = "商品不存在";
            echo json_encode($data);
            exit();
        }

        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $finishedOrderData["finished_order_no"] = "OTS".date('Ymd',time()) . sprintf("%03d", substr(D("FinishedOrder")->count(), -3, 3)+1);
        $finishedOrderData["create_time"] = getCurrentDate();
        $finishedOrderData["finished_product_id"] = $finishedProductId;
        $finishedOrderData["sale_price"] = I("post.salePrice");
//        $finishedOrderData["size"] = I("post.size");
        $sizeNumList = explode('/',I("post.size"));
        $sizeNameList = explode('/',$finishedProduct["size"]);
        $finishedOrderData["size"] = "";
        for($i=0; $i< count($sizeNumList); $i++){
            if($sizeNumList[$i] > 0){
                if(!isNullOrEmpty($finishedOrderData["size"])){
                    $finishedOrderData["size"] .= ", ";
                }
                $finishedOrderData["size"] .= "[". $sizeNameList[$i] ."]x" .$sizeNumList[$i];
            }
        }

        $finishedOrderData["number"] = I("post.number");
        $finishedOrderData["delivery_type"] = I("post.deliveryType");
        $finishedOrderData["receive_name"] = I("post.receiveName");
        $finishedOrderData["receive_address"] = I("post.receiveAddress");
        $finishedOrderData["receive_contact"] = I("post.receiveContact");
        $finishedOrderData["customer_name"] = I("post.customerName");
        $finishedOrderData["patient_name"] = I("post.patientName");
        $finishedOrderData["patient_sex"] = I("post.patientSex");
        $finishedOrderData["patient_age"] = I("post.patientAge");
        $finishedOrderData["doctor_name"] = I("post.doctorName");
        $finishedOrderData["hospital_name"] = I("post.hospitalName");
        $finishedOrderData["payment_type"] = I("post.paymentType");
        $finishedOrderData["note"] = I("post.note");
        $finishedOrderData["need_invoice"] = I("post.needInvoice");
        $finishedOrderData["invoice_name"] = I("post.invoiceName");
        $finishedOrderData["invoice_number"] = I("post.invoiceNumber");
        $finishedOrderData["invoice_detail"] = I("post.invoiceDetail");
        $finishedOrderData["agent_name"] = I("post.agentName");
        $finishedOrderData["total_price"] = $finishedOrderData["sale_price"]*$finishedOrderData["number"];
        $finishedOrderData["employee_id"] = $user["employee_id"];
        if(I("post.needApproval") == 1){
            $finishedOrderData["status"] = -4;
        }else{
            $finishedOrderData["status"] = -1;
        }
        $finishedOrderData["enterprise_code"] = $user["enterprise_code"];
        $nameArr =array();
        array_push($nameArr, "finished_product_id");
        array_push($nameArr, "sale_price");
        array_push($nameArr, "number");
        array_push($nameArr, "delivery_type");
        array_push($nameArr, "receive_name");
        array_push($nameArr, "receive_address");
        array_push($nameArr, "receive_contact");
        array_push($nameArr, "customer_name");
        array_push($nameArr, "note");
        array_push($nameArr, "invoice_name");
        array_push($nameArr, "invoice_number");
        array_push($nameArr, "invoice_detail");
        array_push($nameArr, "agent_name");
        array_push($nameArr, "patient_name");
        array_push($nameArr, "total_price");
        array_push($nameArr, "employee_id");

        $theSame = 1;
        foreach ($nameArr as $name) {
            if($finishedOrderData[$name] != $lastOrder[0][$name]){
                $theSame = -1;
            }
        }

        $minute=floor((strtotime(getCurrentDate())-strtotime($lastOrder[0]["create_time"]))%86400/60);

        if($minute < 2){
            $data["msg"] = $minute;
        }else{
            $theSame = -1;
        }

        if($theSame == 1){
            $data["code"] = -1;
            $data["msg"] .= "订单重复";
            echo json_encode($data);
            exit();
        }

        if(I("post.paymentType") == "微信现结" && I("post.needPay") == "1"){
            $finishedOrderData["status"] = -5;
            $payId = D('Pay')->add(array(
                'out_trade_no' => "PAID".date('Ymd',time()) . sprintf("%03d", substr(D("Pay")->count(), -3, 3)+1),
                'money' => $finishedOrderData["total_price"],
                'status' => 0,
                'type' => 3,
                'callback' => "",
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => 1
            ));

            $finishedOrderData["pay_id"] = $payId;
            $data["finished_order_no"] = $finishedOrderData["finished_order_no"];

            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=". $finishedOrderData["finished_order_id"]."&status=-5";
            $notifyData["first"] = "您已下订单，请支付";
            $notifyData["keyword1"] = $finishedProduct["name"]."(".$finishedOrderData["size"] .")共 ".$finishedOrderData["number"]." 件";
            $notifyData["keyword2"] = $finishedOrderData["finished_order_no"];
            $notifyData["keyword3"] = $finishedOrderData["total_price"]." 元";
            $notifyData["remark"] = "点击查看订单详情。";

            $notifyData["openid"] = $this->customer["openid"];
            OrderUnpaidNotify($notifyData);
        }

        $finishedOrderId = D("FinishedOrder")->add($finishedOrderData);
        $finishedProduct["count"] += $finishedOrderData["number"];
        D("FinishedProduct")->updateInfo($finishedProduct);
//        $data["finished_order_id"] = $finishedOrderId;

        //推送信息到西钓客服
        if($finishedOrderData["status"] == -1){
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=". $finishedOrderId;
            $notifyData["first"] = "收到分销成品订单。";
            if(!isNullOrEmpty($finishedOrderData["patient_name"])){
                $notifyData["first"] .= "患者：" . $finishedOrderData["patient_name"];
            }
            $notifyData["keyword1"] = $finishedOrderData["finished_order_no"];
            if($finishedProduct["class_id"] == "17")
                $notifyData["keyword1"] = "【特殊】" . $notifyData["keyword1"];
            if(!isNullOrEmpty($finishedOrderData["patient_name"])){
                $notifyData["keyword1"] .= ", 患者：" . $finishedOrderData["patient_name"];
            }
            $notifyData["keyword2"] = $finishedProduct["name"]."(".$finishedOrderData["size"] .")共 ".$finishedOrderData["number"]." 件";
            $notifyData["keyword3"] = $finishedOrderData["create_time"];
            $notifyData["keyword4"] = $finishedOrderData["total_price"];
            if(!isNullOrEmpty($finishedOrderData["agent_name"])){
                $notifyData["keyword4"] .= " [" . $finishedOrderData["agent_name"] ."]";
            }
            $notifyData["keyword4"] .= $finishedOrderData["note"];
            $notifyData["keyword5"] = "[" . $finishedOrderData["delivery_type"]."] 下单人：".$user["admin_name"]."(".$finishedOrderData["payment_type"].")";
            $notifyData["remark"] = $finishedOrderData["note"];

//            $adminRoleArr = array("1","8","10");
//            $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
            if($finishedProduct["class_id"] == "17"){
                $notifyData["url"] .= "&classId=17";
                $openidArray = getNotifyArrByName("createFinishedOrderSpecial", $user["enterprise_code"]);
            }

            else
                $openidArray = getNotifyArrByName("createFinishedOrder", $user["enterprise_code"]);
            array_push($openidArray, $user["openid"]);
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                finishedOrderNotify($notifyData);
            }
        }
        if($finishedOrderData["status"] == -4){
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=". $finishedOrderId;
            $notifyData["first"] = "收到待审批分销成品订单 [" . $finishedOrderData["finished_order_no"] ."]";
            $notifyData["keyword1"] = $user["admin_name"];
            $notifyData["keyword2"] = $finishedProduct["name"]."(".$finishedOrderData["size"] .")共 ".$finishedOrderData["number"]." 件，总价：". $finishedOrderData["total_price"] ."元";
            $notifyData["keyword3"] = "下单价：" . $finishedOrderData["sale_price"] ." 元，原价：" . $finishedProduct["price"] ." 元，(".$finishedOrderData["payment_type"].")";
            $notifyData["remark"] = "请审批人点击详情进行审核。";
            if(!isNullOrEmpty($finishedOrderData["note"])){
                $notifyData["remark"] .= " 备注：" . $finishedOrderData["note"];
            }

//            $adminRoleArr = array("1");
//            $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
            $openidArray = getNotifyArrByName("auditFinishedOrder", $user["enterprise_code"]);
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                ApplyApprovalNotify($notifyData);
            }

            $notifyData["openid"] = $user["openid"];
            $notifyData["first"] = "分销成品订单 [" . $finishedOrderData["finished_order_no"]."] 待审批";
            $notifyData["remark"] = "请等待审批人审批。";
            if(!isNullOrEmpty($finishedOrderData["note"])){
                $notifyData["remark"] .= " 备注：" . $finishedOrderData["note"];
            }
            ApplyApprovalNotify($notifyData);
        }

        $data["code"] = 200;
        echo json_encode($data);

    }

    public function createQuickOrder() {

        $finishedProductId = $_REQUEST["finishedProductId"];
        $finishedProduct = D("FinishedProduct")->queryById($finishedProductId);
        $data["code"] = 200;

        if(isNullOrEmpty($finishedProduct)) {
            $data["code"] = -1;
            $data["msg"] = "商品不存在";
            echo json_encode($data);
            exit();
        }

        $finishedOrderData["quick_order_no"] = "QOTS".date('Ymd',time()) . sprintf("%03d", substr(D("QuickOrder")->count(), -3, 3)+1);
        $finishedOrderData["create_time"] = getCurrentDate();
        $finishedOrderData["finished_product_id"] = $finishedProductId;
        $finishedOrderData["sale_price"] = I("post.price");
//        $finishedOrderData["size"] = I("post.size");
        $sizeNumList = explode('/',I("post.size"));
        $sizeNameList = explode('/',$finishedProduct["size"]);
        $finishedOrderData["size"] = "";
        for($i=0; $i< count($sizeNumList); $i++){
            if($sizeNumList[$i] > 0){
                if(!isNullOrEmpty($finishedOrderData["size"])){
                    $finishedOrderData["size"] .= ", ";
                }
                $finishedOrderData["size"] .= "[". $sizeNameList[$i] ."]x" .$sizeNumList[$i];
            }
        }
        $finishedOrderData["type"] = I("post.type");
        $finishedOrderData["number"] = I("post.number");
        $finishedOrderData["delivery_type"] = I("post.deliveryType");
        $finishedOrderData["receive_name"] = I("post.receiveName");
        $finishedOrderData["receive_address"] = I("post.receiveAddress");
        $finishedOrderData["receive_contact"] = I("post.receiveContact");
        $finishedOrderData["payment_type"] = I("post.paymentType");
        $finishedOrderData["note"] = I("post.note");
        $finishedOrderData["need_invoice"] = I("post.needInvoice");
        $finishedOrderData["invoice_name"] = I("post.invoiceName");
        $finishedOrderData["invoice_number"] = I("post.invoiceNumber");
        $finishedOrderData["invoice_detail"] = I("post.invoiceDetail");
        $finishedOrderData["total_price"] = $finishedOrderData["sale_price"]*$finishedOrderData["number"];

        $finishedOrderData["customer_id"] = $this->customer["customer_id"];
        $finishedOrderData["quick_agent_code"] = I("post.quickAgentCode");
        if(I("post.type") == 1){
            $finishedOrderData["status"] = -1;
        }
        if(I("post.type") == 2){
            $finishedOrderData["status"] = -2;
            $payId = D('Pay')->add(array(
                'out_trade_no' => "PAID".date('Ymd',time()) . sprintf("%03d", substr(D("Pay")->count(), -3, 3)+1),
                'money' => $finishedOrderData["total_price"],
                'status' => 0,
                'type' => 2,
                'callback' => "",
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => 1
            ));

            $finishedOrderData["pay_id"] = $payId;
        }




        $finishedOrderId = D("QuickOrder")->add($finishedOrderData);

//        $data["finished_order_id"] = $finishedOrderId;
        if(I("post.type") == 1) {//免付款推送
        //推送信息到客服
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/quickOrderList/?id=". $finishedOrderId."&status=-1";
            $notifyData["first"] = "收到直销成品订单。下单人：".$this->customer["customer_id"]."_".$this->customer["nickname"]."_".$this->customer["realname"];
            $notifyData["keyword1"] = $finishedOrderData["quick_order_no"];
            $notifyData["keyword2"] = $finishedProduct["name"]."(".$finishedOrderData["size"] .")共 ".$finishedOrderData["number"]." 件";
            $notifyData["keyword3"] = $finishedOrderData["create_time"];
            $notifyData["keyword4"] = $finishedOrderData["total_price"];
            $notifyData["keyword5"] = $finishedOrderData["delivery_type"];
            $notifyData["remark"] = "备注：".$finishedOrderData["note"];

//            $adminRoleArr = array("1","8","10");
//            $openidArray = getNotifyArr($adminRoleArr, "xWk202003270001");
            $openidArray = getNotifyArrByName("createQuickOrder", "xWk202003270001");
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                finishedOrderNotify($notifyData);
            }

        //客户单独推送
            $notifyData["openid"] = $this->customer["openid"];
            $notifyData["first"] = "您已下单。";
            finishedOrderNotify($notifyData);
        }
        $data["order_id"] = $finishedOrderId;
        echo json_encode($data);

    }

    public function orderList() {
        $id = $_REQUEST["id"];
        $orderStatus = $_REQUEST["status"];
        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $this->assign("user", $user);
        $this->assign("orderId", $id);
        if($_REQUEST["classId"] != "")
            $this->assign("classId",$_REQUEST["classId"]);
        $this->assign("orderStatus", $orderStatus);
        $this->display("orderList");
    }

    public function myOrderList() {
        $map["fo.status"] = array('neq','-3');
        $status = I("post.status");
        $classId = I("post.classId");
        if(!isNullOrEmpty($classId)) {
            $map["fp.class_id"] = $classId;
        }else{
            $map["fp.class_id"] = array('neq','17');
        }
        if(!isNullOrEmpty($status)) {
            $map["fo.status"] = $status;
        }
        if(!check_role($this->customer["customer_id"], "0,1,3,7,8,10")){
            $map["fo.employee_id"] = $this->customer["customer_id"];
        }
        $orderId = I("post.orderId");
        if(!isNullOrEmpty($orderId) && I("post.ignoreOrderId") != '1') {
            $map["finished_order_id"] = $orderId;
        }
        $employee = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $map["fo.enterprise_code"] = $employee["enterprise_code"];
        $list = D("FinishedOrder")->alias("fo")
            ->join("left join __FINISHED_PRODUCT__ fp on fp.finished_product_id = fo.finished_product_id")
            ->join("left join __ADMIN__ e on e.employee_id = fo.employee_id")
            ->join("left join __ADMIN__ ad on ad.employee_id = fo.delivery_id")
            ->join("left join __ADMIN__ pv on pv.employee_id = fo.approve_id")
            ->where($map)
            ->order("fo.finished_order_id desc")
            ->field("fo.*,fp.price as single_price,fp.image_url,fp.name as finished_product_name, e.admin_name, ad.admin_name as delivery_name, pv.admin_name as approve_name")
            ->select();

        echo json_encode($list);
    }

    public function quickOrderList() {
        $id = $_REQUEST["id"];
        $this->assign("orderId", $id);
        $this->display("quickOrderList");
    }

    public function myQuickOrderList() {
        $status = I("post.status");
        if(!isNullOrEmpty($status)) {
            $map["qo.status"] = $status;
        }
        $orderId = I("post.orderId");
        if(!isNullOrEmpty($orderId)) {
            $map["quick_order_id"] = $orderId;
        }

        if(!check_role($this->customer["customer_id"], "0,1,3,7,8,10")){
            $map["qo.customer_id"] = $this->customer["customer_id"];
        }
        $list = D("QuickOrder")->alias("qo")
            ->join("left join __FINISHED_PRODUCT__ fp on fp.finished_product_id = qo.finished_product_id")
            ->join("left join __CUSTOMER__ c on c.customer_id = qo.customer_id")
//            ->join("left join __ADMIN__ e on e.employee_id = fo.employee_id")
//            ->join("left join __ADMIN__ ad on ad.user_id = fo.delivery_id")
            ->where($map)
            ->order("qo.quick_order_id desc")
            ->field("qo.*,fp.image_url,fp.name as finished_product_name, c.customer_id, c.nickname, c.realname")
            ->select();
        echo json_encode($list);
    }

    public function orderCart() {
        $orderStatus = $_REQUEST["status"];
        $this->assign("orderStatus", $orderStatus);
        $this->display("orderCart");
    }

    public function myOrderCart() {
        $map["fo.status"] = "-3";
        $map["fo.employee_id"] = $this->customer["customer_id"];
        $list = D("FinishedOrder")->alias("fo")
            ->join("left join __FINISHED_PRODUCT__ fp on fp.finished_product_id = fo.finished_product_id")
            ->join("left join __ADMIN__ e on e.employee_id = fo.employee_id")
            ->join("left join __ADMIN__ ad on ad.employee_id = fo.delivery_id")
            ->where($map)
            ->order("fo.finished_order_id desc")
            ->field("fo.*,fp.price as single_price,fp.image_url,fp.name as finished_product_name, e.admin_name, ad.admin_name as delivery_name")
            ->select();

        echo json_encode($list);
    }

    public function addCart() {

        $finishedProductId = $_REQUEST["finishedProductId"];
        $finishedProduct = D("FinishedProduct")->queryById($finishedProductId);
        $data["code"] = 200;

        if(isNullOrEmpty($finishedProduct)) {
            $data["code"] = -1;
            $data["msg"] = "商品不存在";
            echo json_encode($data);
            exit();
        }

        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $finishedOrderData["finished_order_no"] = "OTS".date('Ymd',time()) . sprintf("%03d", substr(D("FinishedOrder")->count(), -3, 3)+1);
        $finishedOrderData["create_time"] = getCurrentDate();
        $finishedOrderData["finished_product_id"] = $finishedProductId;
        $finishedOrderData["sale_price"] = I("post.salePrice");
        $sizeNumList = explode('/',I("post.size"));
        $sizeNameList = explode('/',$finishedProduct["size"]);
        $finishedOrderData["size"] = "";
        for($i=0; $i< count($sizeNumList); $i++){
            if($sizeNumList[$i] > 0){
                if(!isNullOrEmpty($finishedOrderData["size"])){
                    $finishedOrderData["size"] .= ", ";
                }
                $finishedOrderData["size"] .= "[". $sizeNameList[$i] ."]x" .$sizeNumList[$i];
            }
        }

        $finishedOrderData["number"] = I("post.number");
        $finishedOrderData["agent_name"] = I("post.agentName");
        $finishedOrderData["total_price"] = $finishedOrderData["sale_price"]*$finishedOrderData["number"];
        $finishedOrderData["employee_id"] = $user["employee_id"];
        $finishedOrderData["status"] = -3;
        $finishedOrderData["enterprise_code"] = $user["enterprise_code"];

        $finishedOrderId = D("FinishedOrder")->add($finishedOrderData);
        $finishedProduct["count"] += $finishedOrderData["number"];
        D("FinishedProduct")->updateInfo($finishedProduct);
        $data["code"] = 200;
        echo json_encode($data);

    }

    public function removeOrder() {

        $id = $_REQUEST['id'];
        D("FinishedOrder")->deleteById($id);

        $this->display("orderCart");
    }

    public function submitCart() {
        $map["fo.status"] = "-3";
        $map["fo.employee_id"] = $this->customer["customer_id"];
        $cartList = D("FinishedOrder")->alias("fo")
            ->join("left join __FINISHED_PRODUCT__ fp on fp.finished_product_id = fo.finished_product_id")
            ->where($map)
            ->field("fo.*,fp.name as finished_product_name")
            ->select();

        $data["code"] = 200;
        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        foreach ($cartList as $finishedOrderData) {
            $finishedOrderData["create_time"] = getCurrentDate();
            $finishedOrderData["delivery_type"] = I("post.deliveryType");
            $finishedOrderData["receive_name"] = I("post.receiveName");
            $finishedOrderData["receive_address"] = I("post.receiveAddress");
            $finishedOrderData["receive_contact"] = I("post.receiveContact");
            $finishedOrderData["patient_name"] = I("post.patientName");
            $finishedOrderData["payment_type"] = I("post.paymentType");
            $finishedOrderData["note"] = I("post.note");
            $finishedOrderData["need_invoice"] = I("post.needInvoice");
            $finishedOrderData["invoice_name"] = I("post.invoiceName");
            $finishedOrderData["invoice_number"] = I("post.invoiceNumber");
            $finishedOrderData["invoice_detail"] = I("post.invoiceDetail");
            $finishedOrderData["status"] = -1;
            D("FinishedOrder")->updateInfo($finishedOrderData);

            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=". $finishedOrderData["finished_order_id"];
            $notifyData["first"] = "收到分销成品订单。";
            if(!isNullOrEmpty($finishedOrderData["patient_name"])){
                $notifyData["first"] .= "患者：" . $finishedOrderData["patient_name"];
            }
            $notifyData["keyword1"] = $finishedOrderData["finished_order_no"];
            if(!isNullOrEmpty($finishedOrderData["patient_name"])){
                $notifyData["keyword1"] .= ", 患者：" . $finishedOrderData["patient_name"];
            }
            $notifyData["keyword2"] = $finishedOrderData["finished_product_name"]."(".$finishedOrderData["size"] .")共 ".$finishedOrderData["number"]." 件";
            $notifyData["keyword3"] = $finishedOrderData["create_time"];
            $notifyData["keyword4"] = $finishedOrderData["total_price"];
            if(!isNullOrEmpty($finishedOrderData["agent_name"])){
                $notifyData["keyword4"] .= " [" . $finishedOrderData["agent_name"] ."]";
            }
            $notifyData["keyword4"] .= $finishedOrderData["note"];
            $notifyData["keyword5"] = "[" . $finishedOrderData["delivery_type"]."] 下单人：".$user["admin_name"] . "(".$finishedOrderData["payment_type"].")";
            $notifyData["remark"] = $finishedOrderData["note"];

//            $adminRoleArr = array("1","8","10");
//            $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
            $openidArray = getNotifyArrByName("createFinishedOrder", $user["enterprise_code"]);
            array_push($openidArray, $user["openid"]);
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                finishedOrderNotify($notifyData);
            }
        }
        echo json_encode($data);

    }

    public function approve($orderId, $status) {
        $data["code"] = 200;
        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();

        $finishedOrderData = D("FinishedOrder")->queryById($orderId);
        if($finishedOrderData["status"] != -4){
            $data["message"] = "工单已审批过，无需重复审批。";
            echo json_encode($data);
            return;
        }
        $finishedOrderData["status"] = $status;
        $finishedOrderData["approve_id"] = $user["employee_id"];
        $finishedOrderData["approve_time"] = getCurrentDate();
        D("FinishedOrder")->updateInfo($finishedOrderData);
        $finishedProduct = D("FinishedProduct")->queryById($finishedOrderData["finished_product_id"]);
        $sales = D("admin")->where(array('employee_id'=>$finishedOrderData["employee_id"]))->find();
        if($status == -1) {
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=" . $finishedOrderData["finished_order_id"];
            $notifyData["first"] = "收到分销成品订单。";
            if(!isNullOrEmpty($finishedOrderData["patient_name"])){
                $notifyData["first"] .= "患者：" . $finishedOrderData["patient_name"];
            }
            $notifyData["keyword1"] = $finishedOrderData["finished_order_no"];
            if(!isNullOrEmpty($finishedOrderData["patient_name"])){
                $notifyData["keyword1"] .= ", 患者：" . $finishedOrderData["patient_name"];
            }
            $notifyData["keyword2"] = $finishedProduct["name"] . "(" . $finishedOrderData["size"] . ")共 " . $finishedOrderData["number"] . " 件";
            $notifyData["keyword3"] = $finishedOrderData["create_time"];
            $notifyData["keyword4"] = $finishedOrderData["total_price"];
            if (!isNullOrEmpty($finishedOrderData["agent_name"])) {
                $notifyData["keyword4"] .= " [" . $finishedOrderData["agent_name"] . "]";
            }
            $notifyData["keyword4"] .= $finishedOrderData["note"];
            $notifyData["keyword5"] = "[" . $finishedOrderData["delivery_type"] . "] 下单人：" . $sales["admin_name"] . "(".$finishedOrderData["payment_type"].")";
            $notifyData["remark"] = $finishedOrderData["note"];

//            $adminRoleArr = array("1", "8", "10");
//            $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
            $openidArray = getNotifyArrByName("createFinishedOrder", $user["enterprise_code"]);
//            array_push($openidArray, $user["openid"]);
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                finishedOrderNotify($notifyData);
            }
            $notifyData["first"] = "分销成品订单 [" . $finishedOrderData["finished_order_no"] ."] 审批通过。";
            $notifyData["keyword2"] = "审批通过";
        }else{
            $notifyData["first"] = "分销成品订单 [" . $finishedOrderData["finished_order_no"] ."] 审批未通过。";
            $notifyData["keyword2"] = "审批未通过";
        }

        $notifyData["keyword1"] = $finishedProduct["name"]."(".$finishedOrderData["size"] .")共 ".$finishedOrderData["number"]." 件，总价：". $finishedOrderData["total_price"] ."元";
        $notifyData["keyword3"] = "审批人：" . $user["admin_name"] . "，下单人：" . $sales["admin_name"];
        $notifyData["keyword4"] = getCurrentDate();
        $notifyData["remark"] = null;
        $notifyData["url"] = null;
        $openidArray = array($user["openid"],$sales["openid"]);
        $openidArray = array_unique($openidArray);
        foreach ($openidArray as $openid) {
            $notifyData["openid"] = $openid;
            ApprovalResultNotify($notifyData);
        }
//        $data["message"] = $finishedOrderData["status"];
        echo json_encode($data);
    }

    public function spio() {
        $employee = D("Admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $employeeRole = explode(',',$employee["role"]);
        $this->assign("employeeRole", $employeeRole);

        $this->assign("employee", $employee);
        $this->display("spio");
    }

    public function couponOrder() {
        $couponCode = $_REQUEST["couponCode"];

        $coupon = D("Coupon")->where(array('coupon_code'=>$couponCode))->find();

        if(isNullOrEmpty($coupon)){
            $this->error("无效产品链接！");
            exit();
        }

        $product = D("Product")->queryById($coupon["product_id"]);

        $this->assign("customer", $this->customer);
        $this->assign("product", $product);
        $this->assign("coupon", $coupon);
        $this->display("couponOrder");

    }
}